package com.zhang;

import com.zhang.config.WebMvcConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;

/**
 * 主启动类
 */
public class MainStart {


    public MainStart(){
        //创建一个tomcat服务器
        Tomcat tomcat = new Tomcat();
        //开启8080端口
        tomcat.setPort(8088);
        //开启http引擎
        tomcat.getConnector();

        //添加上下文
        Context context = tomcat.addContext("", null);
        //创建应用上下文，springMvc的IOC容器
        WebApplicationContext applicationContext = createApplicationContext(context.getServletContext());

        //浏览器的所有请求都会被DispatcherServlet统一接受处理、
        //请求的URL路径通过HandlerMapping去匹配controller中的路径，因为在应用上下文中我们将IOC容器已经加载过来,
        //得到HandlerAdapter对象，对应的应用控制器的方法
        DispatcherServlet servlet = new DispatcherServlet(applicationContext);
        Wrapper dispatcher = tomcat.addServlet(context, "", servlet);
        dispatcher.setLoadOnStartup(0);
        dispatcher.addMapping("/*");

        try {
            //启动tomcat服务器
            tomcat.start();
        } catch (LifecycleException e) {
            e.printStackTrace();
        }

    }


    /**
     * 创建springMvc的应用上下文
     * @param servletContext
     * @return
     */
    public static WebApplicationContext createApplicationContext(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext ctx
                = new AnnotationConfigWebApplicationContext();
        ctx.register(WebMvcConfig.class);

        ctx.setServletContext(servletContext);
        ctx.refresh();
        ctx.registerShutdownHook();
        return ctx;
    }

    public static void main(String[] args) {
        new MainStart();
    }
}
























